<template>
  <a-modal
    :title="`${info.userId?'编辑':'添加'}用户`"
    :dialogStyle="{top:'10px'}"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @cancel="handleCancel"
    @ok="handleSubmit"
  >
    <a-form-model
      ref="ruleForm"
      layout="horizontal"
      :model="form"
      :rules="rules"
      :labelCol="{span:5}"
      :wrapperCol="{span:16}">
      <a-form-model-item label="用户名" prop="username">
        <a-input v-model="form.username" />
      </a-form-model-item>
      <a-form-model-item label="真实姓名" prop="realname">
        <a-input v-model="form.realname" />
      </a-form-model-item>
      <a-form-model-item label="单位名称" prop="unitName">
        <a-input v-model="form.unitName" />
      </a-form-model-item>
      <a-form-model-item label="手机号" prop="phone">
        <a-input v-model="form.phone" :max-length="11" />
      </a-form-model-item>
      <a-form-model-item label="密码" prop="password">
        <a-input v-model="form.password" type="password">
          <a slot="suffix" @click="onResetPasswrod">
            <a-tooltip title="重置密码：123456">重置</a-tooltip>
          </a>
        </a-input>
      </a-form-model-item>
      <a-form-model-item label="确认密码" prop="checkPass">
        <a-input type="password" v-model="form.checkPass" />
      </a-form-model-item>
      <a-form-model-item label="积分" prop="points">
        <a-input-number id="inputNumber" style="width: 200px" v-model="form.points" :min="-1" disabled />
        <a-button type="primary" @click="onResetPoints">重置</a-button>
      </a-form-model-item>
      <a-form-model-item label="状态" prop="status">
        <a-radio-group name="radioGroup" v-model="form.status">
          <a-radio :value="1">启用</a-radio>
          <a-radio :value="0">停用</a-radio>
        </a-radio-group>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { addUser, editUser } from '@/api/user'
import { getPoints } from '@/api/manage'

export default {
  name: 'UserInfo',
  props: {
    info: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      visible: false,
      confirmLoading: false,
      form: {
        username: '',
        realname: '',
        unitName: '',
        password: '',
        phone: '',
        status: 1,
        points: -1,
        checkPass: '',
        roles: []
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        realname: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        unitName: [
          { required: true, message: '请输入单位名称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请输入密码'))
              } else {
                if (this.form.checkPass !== '') {
                  this.$refs.ruleForm.validateField('checkPass')
                }
                callback()
              }
            },
            trigger: 'blur'
          }],
        checkPass: [
          {
            validator: (rule, value, callback) => {
              console.log(value, this.form)
              if (value === '') {
                callback(new Error('请输入确认密码'))
              } else if (value !== this.form.password) {
                callback(new Error('两次密码不一致'))
              }
              callback()
            },
            trigger: 'blur'
          }]
      }
    }
  },
  created () {
    this.visible = true
    if (this.info.userId) {
      for (const key in this.info) {
        this.form[key] = this.info[key]
      }
      this.form.checkPass = JSON.parse(JSON.stringify(this.info.password))
    } else {
      getPoints().then(response => {
        this.form.points = response.data.defaultPoints
      })
    }
  },
  methods: {
    onResetPoints () {
      const that = this
      this.$confirm({
        title: '系统提示',
        content: `确定重置积分吗？`,
        onOk () {
          getPoints().then(response => {
            that.form.points = response.data.defaultPoints
          })
        }
      })
    },
    handleSubmit () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          const form = { ...this.form }
          if (form.userId) {
            editUser(form).then(() => {
              this.$message.success('编辑用户成功')
              this.handleCancel(false)
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            addUser(form).then(() => {
              this.$message.success('添加用户成功')
              this.handleCancel(true)
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    onResetPasswrod () {
      this.form.password = '123456'
      this.form.checkPass = ''
    },
    handleCancel (isRef) {
      this.visible = false
      this.$emit('close', isRef)
    }
  }
}
</script>

<style scoped>

</style>
